package com.rbac.admin.service.system.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.admin.entity.system.SystemUserDept;
import com.rbac.admin.mapper.system.UserDeptMapper;
import com.rbac.admin.service.system.UserDeptService;
import com.rbac.admin.vo.system.DeptVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户部门关联服务实现类
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@Service
public class UserDeptServiceImpl extends ServiceImpl<UserDeptMapper, SystemUserDept> implements UserDeptService {
    
    @Autowired
    private UserDeptMapper userDeptMapper;
    
    @Override
    public List<DeptVO> getDeptsByUserId(String userId) {
        return userDeptMapper.selectDeptsByUserId(userId);
    }
    
    @Override
    public DeptVO getMainDeptByUserId(String userId) {
        return userDeptMapper.selectMainDeptByUserId(userId);
    }
    
    @Override
    @Transactional
    public void saveUserDepts(String userId, List<Integer> deptIds, Integer mainDeptId) {
        if (deptIds == null || deptIds.isEmpty()) {
            return;
        }
        
        List<SystemUserDept> userDeptList = new ArrayList<>();
        for (Integer deptId : deptIds) {
            SystemUserDept userDept = new SystemUserDept();
            userDept.setUserId(userId);
            userDept.setDeptId(deptId);
            // 设置主部门标志
            userDept.setIsMain(deptId.equals(mainDeptId) ? 1 : 0);
            userDeptList.add(userDept);
        }
        
        // 批量插入
        userDeptMapper.batchInsert(userDeptList);
    }
    
    @Override
    @Transactional
    public void updateUserDepts(String userId, List<Integer> deptIds, Integer mainDeptId) {
        // 先删除原有关联
        deleteUserDeptsByUserId(userId);
        
        // 再保存新的关联
        saveUserDepts(userId, deptIds, mainDeptId);
    }
    
    @Override
    @Transactional
    public void deleteUserDeptsByUserId(String userId) {
        userDeptMapper.deleteByUserId(userId);
    }
}